package com.jrx.anytxn.reporting.job.lsPuHui.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.BreakContractConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class BreakContractListener implements JobExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(BreakContractListener.class);

    @Autowired
    private BreakContractConfig breakContractConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        String toDay = DateUtils.format(org.getToday(),"yyyyMMdd");

        String reportingPath = breakContractConfig.getFilePath();
        String filePath = reportingPath + org.getTenantId() + File.separator + toDay + File.separator;

        String fileName = ReportingConstant.LS_BREAK_CONTRACT + "_" + breakContractConfig.getFileName() + ".dat";
        Path reportingFile = Paths.get(filePath + fileName);
        try {
            Files.deleteIfExists(reportingFile);
        } catch (IOException e) {
            logger.error("删除个人贷款违约文件失败",e);
        }


        Path pFile = Paths.get(filePath);

        if (!Files.isDirectory(pFile)) {
            //创建文件夹
            try {
                Files.createDirectories(pFile);
            } catch (IOException e) {
                logger.error("创建目录失败",e);
            }
        }

        //创建文件
        try {
            Files.createFile(reportingFile);
        } catch (IOException e) {
            logger.error("创建个人贷款违约文件失败",e);
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }
}
